package com.example.config;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
	
	private static Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);

	/**
	 * 缓存管理器.
	 * 
	 * @param redisTemplate
	 * @return
	 */
	@Bean
	public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
		CacheManager cacheManager = new RedisCacheManager(redisTemplate);
		return cacheManager;
	}

	/**
	 * redis模板操作类,类似于jdbcTemplate的一个类;
	 *
	 * 虽然CacheManager也能获取到Cache对象，但是操作起来没有那么灵活；
	 * 这里在扩展下：RedisTemplate这个类不见得很好操作，我们可以在进行扩展一个我们 自己的缓存类，比如：RedisStorage类;
	 * 
	 * @param factory
	 *            : 通过Spring进行注入，参数在application.properties进行配置；
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Bean
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		StringRedisTemplate template = new StringRedisTemplate(factory);  
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);  
        ObjectMapper om = new ObjectMapper();  
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
        jackson2JsonRedisSerializer.setObjectMapper(om);  
        template.setValueSerializer(jackson2JsonRedisSerializer);  
        template.afterPropertiesSet();  
        return template;
	}
	
	/**
	 * redis缓存主键生成规则
	 * DigestUtils.md5Hex (包名 + 方法名 + 参数（实体类参数采用获取其toString()方法,其他参数均直接toString();多个参数拼接）)
	 * 如果有实体类作为参数，请务必重写该实体类的toString()方法并且该实体类是继承于PageVo类或者SysEntity类
	 * @return
	 */
	 @Bean  
	 public KeyGenerator wiselyKeyGenerator(){
		logger.info("############redis主键生成策略#################");
        return new KeyGenerator() {
			@SuppressWarnings({ "rawtypes", "unchecked" })
			@Override
			public Object generate(Object target, Method method, Object... params) {
				if(AopUtils.isCglibProxy(target)){
					//System.out.println("CglibProxy");
				}
				System.out.println(target.getClass().getName());
				StringBuilder sb = new StringBuilder();  
                sb.append(target.getClass().getPackage());  
                sb.append(method.getName());  
                for (Object obj : params) {
                	if(obj instanceof Page || obj instanceof Model){
                		 try {
							Class clazz = obj.getClass();
							 Method m = clazz.getDeclaredMethod("toString");
							 String str = m.invoke(obj).toString();
							 sb.append(str);
						} catch (Exception e) {
							logger.info("redis主键生成KeyGenerator异常:",e);
						}
    				}else{
    					if(null != obj){
    						sb.append(obj.toString());  
    					}
    				}
                }
                logger.info("toString:" + sb.toString());
                String key = DigestUtils.md5DigestAsHex(sb.toString().getBytes());
                logger.info("KeyGenerator:" + key);
                return key;
			} 
        };  
    }
}
